import React, { useEffect } from 'react';
import { Form, Input, Button, Checkbox, Card, message } from 'antd';
import { Link, useNavigate } from 'react-router-dom';
import './LoginPage.css';

const LoginPage = props => {
  const { setLoggedIn } = props;
  const history = useNavigate();

  useEffect(() => {
    const token = sessionStorage.getItem('token');
    if (token) {
      history('/');
    }
  }, [history]);

  const handleLogin = async values => {
    console.log('Received values of form: ', values);
    const requestOptions = {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        username: values.username,
        password: values.password,
      }),
    };
    try {
      const response = await fetch(
        'http://localhost:29157/api/users/login',
        requestOptions
      );
      const data = await response.json();
      if (response.ok) {
        if (data.data == null) {
          message.error('用户名密码错误，请重新登录');
        } else {
          console.log('Login success:', data);
          setLoggedIn(true);
          sessionStorage.setItem('token', data.data.access_token); // Store the token in sessionStorage
          history('/*');
        }
      } else {
        console.error('Login error:', data);
      }
    } catch (error) {
      console.error('Network error:', error);
    }
  };

  return (
    <div className='login-page'>
      <div className='bookmark'>
        <div className='bookmark-tag'></div>
        <div className='bookmark-text'>
          <h2 className='intro-title'>神奇笔记本</h2>
          <p className='intro-description'>
            一个帮助你记录生活点滴的个人管理系统
          </p>
        </div>
      </div>
      <div className='login-content'>
        <Card className='login-card'>
          <h2 className='login-title'>欢迎登录</h2>
          <Form
            name='login-form'
            initialValues={{ remember: true }}
            onFinish={handleLogin}>
            <Form.Item
              name='username'
              rules={[{ required: true, message: '请输入用户名！' }]}>
              <Input placeholder='用户名' />
            </Form.Item>

            <Form.Item
              name='password'
              rules={[{ required: true, message: '请输入密码！' }]}>
              <Input.Password placeholder='密码' />
            </Form.Item>

            <Form.Item>
              <Form.Item
                name='remember'
                valuePropName='checked'
                noStyle>
                <Checkbox>记住我</Checkbox>
              </Form.Item>
              <a
                href='#'
                className='login-form-forgot'>
                忘记密码
              </a>
            </Form.Item>

            <Form.Item>
              <Button
                type='primary'
                htmlType='submit'
                className='login-form-button'>
                登录
              </Button>
              <div style={{ marginTop: '16px' }}>
                <Link to='/register'>没有账号？点击注册</Link> {/* 注册链接 */}
              </div>
            </Form.Item>
          </Form>
        </Card>
      </div>
      <div className='login-footer'>
        <p className='footer-text'>
          Made by 赵文博 with React, Redux, and Ant Design
        </p>
      </div>
    </div>
  );
};
export default LoginPage;
